package com.ruoyi.ly.service.impl;


import cn.hutool.core.date.DateUtil;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.config.properties.MinioProperties;
import com.ruoyi.ly.service.FileUploadService;
import io.minio.*;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private Environment environment;
    @Autowired
    private ServerConfig serverConfig;

    //图片上传
    @Override
    public String upload(MultipartFile file)  {
        try {
            /**
             * 内部服务器无法访问 http://118.25.51.62:9000处理
             * 根据环境判断,若为测试环境则走本地服务，反则走minio
             */
            // 获取 spring.profiles.active 的值
            String activeProfile = environment.getProperty("spring.profiles.active");
            System.out.println(activeProfile);
            if("test".equals(activeProfile)){
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                return url;
            }
            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecreKey())
                    .build();

            // 判断桶是否存在
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {       // 如果不存在，那么此时就创建一个新的桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'ly-bucket' already exists.");
            }

            // 设置存储对象名称       使用uuid让每个上传文件名字唯一  根据日期生成每一天的文件夹
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //20230801/443e1e772bef482c95be28704bec58a901.jpg
            String fileName = dateDir+"/"+uuid+file.getOriginalFilename();
            System.out.println(fileName);

            // 输入流需要关闭,使用 @Cleanup 注解,否则会报异常
            @Cleanup
            InputStream inputStream = file.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .stream(inputStream, file.getSize(), -1)
                    .object(fileName)
                    .build();
            minioClient.putObject(putObjectArgs) ;

            //获取上传文件在minio路径
            String url =minioProperties.getEndpointUrl() + "/" + minioProperties.getBucketName() + "/" + fileName ;

            return url;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }

    }
}
